library(tidyverse)

ruta <- "C:/Users/Matias/Dropbox/Proyectos/Fondecyt Participacion Electoral/Articulos/Electoral Winners y Plebiscito/Harvard Dataverse/2. Constitutional Plebiscite (study 2)/"
load(paste0(ruta,"2. Database/ola_1.Rdata"))
load(paste0(ruta,"2. Database/ola_2.Rdata"))

ola_1 <- ola_1 %>% mutate_at(vars(starts_with(c("date")),ends_with("date")),
                             function(x)as.character(x)) %>%
  rename_at(vars(-id),function(x)paste0(x,"_w01"))

ola_2 <- ola_2 %>% mutate_at(vars(starts_with("date"),ends_with("date")),
                             function(x)as.character(x)) %>%
  rename_at(vars(-id),function(x)paste0(x,"_w02"))

# Merge de las bases de datos

enc_wide <- left_join(ola_1,ola_2,by="id")

enc_wide$atricion <- with(enc_wide,case_when(is.na(datestamp_w02)~"Atricion",
                           !is.na(datestamp_w02)~"Permanece"))

save(enc_wide,file=
       paste0(ruta,"2. Database/Encuesta Wide (No Recodificada).Rdata"))

# Base long

enc_long <- pivot_longer(enc_wide,cols=matches("_w"),names_to = c(".value","ola"),
                     names_sep = "_w0",values_drop_na = T)
enc_long$ola <- factor(enc_long$ola,
                       levels = c(1,2),labels = c("Pre-Eleccion","Post-Eleccion"))

save(enc_long,file=
       paste0(ruta,"2. Database/Encuesta Long.Rdata"))

# Quitar sufijos

ola_1 <- ola_1  %>% rename_at(vars(-id),function(x) gsub(pattern ="_w01",replacement = "",x = x))
ola_2 <- ola_2  %>% rename_at(vars(-id),function(x) gsub(pattern ="_w02",replacement = "",x = x))


